"""
@Author: li
@Email: lijianqiao2906@live.com
@FileName: menu.py
@DateTime: 2025/07/06
@Docs: 菜单管理API
"""

from typing import Any, cast

from fastapi import APIRouter, Depends

from app.models import Menu
from app.schemas.menu import MenuCreate, MenuNode, MenuRead, MenuUpdate
from app.services.system import menu_service
from app.utils.deps import PermissionChecker

router = APIRouter()


@router.get(
    "/tree",
    response_model=list[MenuNode],
    summary="获取菜单树",
    dependencies=[Depends(PermissionChecker("menu:read"))],
)
async def get_menu_tree() -> list[Menu]:
    """
    获取所有菜单并以树形结构返回。
    """
    return await menu_service.get_menu_tree()


@router.post(
    "/",
    response_model=MenuRead,
    summary="创建新菜单",
    dependencies=[Depends(PermissionChecker("menu:create"))],
)
async def create_menu(menu_in: MenuCreate) -> Menu:
    """
    创建新菜单项。
    """
    menu_model = await menu_service.create(**menu_in.model_dump())
    return cast(Menu, menu_model)


@router.get(
    "/{menu_id}",
    response_model=MenuRead,
    summary="获取单个菜单",
    dependencies=[Depends(PermissionChecker("menu:read"))],
)
async def get_menu_by_id(menu_id: int) -> Menu:
    """
    根据ID获取单个菜单项的详细信息。
    """
    menu_model = await menu_service.get_by_id(id=menu_id)
    return cast(Menu, menu_model)


@router.put(
    "/{menu_id}",
    response_model=MenuRead,
    summary="更新菜单",
    dependencies=[Depends(PermissionChecker("menu:update"))],
)
async def update_menu(menu_id: int, menu_in: MenuUpdate) -> Menu:
    """
    更新指定ID的菜单项。
    """
    menu_model = await menu_service.update(id=menu_id, **menu_in.model_dump(exclude_unset=True))
    return cast(Menu, menu_model)


@router.delete(
    "/{menu_id}",
    response_model=dict[str, Any],
    summary="删除菜单",
    dependencies=[Depends(PermissionChecker("menu:delete"))],
)
async def delete_menu(menu_id: int) -> dict[str, Any]:
    """
    删除指定ID的菜单项。
    """
    await menu_service.delete(id=menu_id)
    return {"message": "菜单删除成功"}
